package com.deng.seata.tcc.account.facade.impl;

import com.alibaba.fastjson.JSON;
import com.deng.seata.tcc.account.facade.AccountFacade;
import com.deng.seata.tcc.account.facade.request.AccountRequest;
import com.deng.seata.tcc.account.facade.response.AccountResponse;
import com.deng.seata.tcc.account.service.AccountService;
import com.deng.seata.tcc.account.utils.ResultHolder;
import io.seata.core.context.RootContext;
import io.seata.rm.tcc.api.BusinessActionContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Desc:
 * @Date: 2024/5/19 12:00
 * @Auther: dengyanliang
 */
@Slf4j
@Component("accountFacade")
public class AccountFacadeImpl implements AccountFacade {

    @Autowired
    private AccountService transferService;

    @Override
    public AccountResponse transferTCC(AccountRequest request) {
        log.info("request:{}", JSON.toJSONString(request));

        String xid = RootContext.getXID(); // 全局事务id
        log.info("全局事务事务ID------>{}", xid);

        AccountResponse response = new AccountResponse();
        transferService.transfer(request);
        response.setCode("1000");
        response.setMessage("成功");
        return response;
    }

    @Override
    public void transferCommit(BusinessActionContext actionContext) {
        // 防幂等控制
        String xid = actionContext.getXid();
        String actionOneResult = ResultHolder.getActionResult(xid);
        if(StringUtils.isNotBlank(actionOneResult)){
            log.info("》》》》transferCommit 已经提交过了, xid: {}",xid);
            return;
        }
        ResultHolder.setActionResult(xid,"T");

        String requestString = actionContext.getActionContext("accountRequest").toString();
        log.info("》》》》transferCommit 请求信息：{}", requestString);
        AccountRequest accountRequest = JSON.parseObject(requestString, AccountRequest.class);
        transferService.transferCommit(accountRequest);
    }

    @Override
    public void transferCancel(BusinessActionContext actionContext) {
        // 防幂等控制
        String xid = actionContext.getXid();
        String actionOneResult = ResultHolder.getActionResult(xid);
        if(StringUtils.isNotBlank(actionOneResult)){
            log.info("》》》》transferCancel 已经提交过了, xid: {}",xid);
            return;
        }
        ResultHolder.setActionResult(xid,"C");

        String requestString = actionContext.getActionContext("accountRequest").toString();
        log.info("》》》》transferCancel 请求信息：{}", requestString);
        AccountRequest accountRequest = JSON.parseObject(requestString, AccountRequest.class);
        transferService.transferCancel(accountRequest);
    }
}

